<template>
  <div class="avue-tags"
       v-if="showTag">
<!--    <div v-if="oc" style="display: flex;height: 30px;margin-bottom: 6px;">-->
<!--      <div style="margin: 0 auto;font-size: 18px;">订单:-->
<!--        <el-select clearable size="medium" v-model="offerId" @change="offerCallback" style="size: 400px; width:400px;" filterable>-->
<!--          <el-option v-for="(item,index) in offerList" :key="index" :label="item.name + ' ('+item.id + ')'" :value="item.id"></el-option>-->
<!--        </el-select>-->
<!--        <el-button @click="viewOfferInfo">订单详情</el-button>-->
<!--      </div>-->
<!--    </div>-->
    <!-- tag盒子 -->
    <div v-if="contextmenuFlag"
         class="avue-tags__contentmenu"
         :style="{left:contentmenuX+'px',top:contentmenuY+'px'}">
      <div class="item"
           @click="clearCacheTags">{{ $t('tagsView.clearCache') }}
      </div>
      <div class="item"
           @click="closeOthersTags">{{ $t('tagsView.closeOthers') }}
      </div>
      <div class="item"
           @click="closeAllTags">{{ $t('tagsView.closeAll') }}
      </div>
    </div>
    <div class="avue-tags__box"
         :class="{'avue-tags__box--close':!website.isFirstPage}"
         style="display: flex;justify-content: space-between;">

      <el-tabs v-model="active"
               type="card"
               @contextmenu.native="handleContextmenu"
               :closable="tagLen!==1"
               @tab-click="openTag"
               @edit="menuTag">
        <el-tab-pane :key="getLastSameNameTag(item,index + 1).value"
                     v-for="(item,index) in tagList"
                     v-if="!hasSameName(item,index)"
                     :label="generateTitle(item)"
                     :name="getLastSameNameTag(item,index + 1).value">
        </el-tab-pane>

      </el-tabs>
<!--      <el-button type="text" disabled>版本号: 0.8.10</el-button>-->
      <el-dropdown class="avue-tags__menu">
        <el-button type="primary"
                   size="mini">
          {{ $t('tagsView.menu') }}
          <i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item @click.native="$parent.isSearch=true">{{ $t('tagsView.search') }}</el-dropdown-item>
          <el-dropdown-item @click.native="closeOthersTags">{{ $t('tagsView.closeOthers') }}</el-dropdown-item>
          <el-dropdown-item @click.native="closeAllTags">{{ $t('tagsView.closeAll') }}</el-dropdown-item>
          <el-dropdown-item @click.native="clearCacheTags">{{ $t('tagsView.clearCache') }}</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>

    <offer-edit :title="offerInfo.title" :offerStatus="offerInfo.status" :dialogVisible="offerInfo.visible"
                :dataList="offerInfo.data" @close-dialog="closeOfferDialog" :confirm-to-share="offerInfo.confirmToShare"></offer-edit>

  </div>

</template>
<script>
import {mapGetters, mapState} from "vuex";
import {clearCache} from "@/api/user";
import {getOfferList} from "@/api/business/share"
import store from '@/store/'
import { getEventMgr, createEventHandler  } from "@/util/events";
import offerEdit from "@/views/business/components/offerEdit"
import {getDetail} from "@/api/business/offer";

export default {
  name: "tags",
  components: {
    offerEdit,
  },
  data() {
    return {
      active: "",
      contentmenuX: "",
      contentmenuY: "",
      contextmenuFlag: false,
      offerList: [],//offer列表
      aa:[],
      offerId:store.state.user.offer +'',//选中的offer
      oc: '',
      offerInfo: {
        visible: false,
        title: '',
        status: '',
        data: null,
        confirmToShare: 0,
      },
    };
  },
  beforeRouteLeave(to, form, next) {
    let self = this;
    if(self.eventHandler) {
      self.eventHandler.clear();
    }
    next();
  },
  created() {
    let self = this;
    this.eventHandler = createEventHandler("offerCenter").addListener(
      (event) => {
        if (
          event.message == "viewOfferInfo" &&
          event.offerId &&
          event.offerId !== ""
        ) {
          self.viewOfferInfo();
        }
      }
    );
  },
  mounted() {
    this.setActive();
    this.getOfferDic();
  },
  watch: {
    tag() {
      this.setActive();
    },
    contextmenuFlag() {
      window.addEventListener("mousedown", this.watchContextmenu);
    },
    userInfo() {
      this.getOfferDic();
    }
  },
  computed: {
    ...mapGetters(["tagWel", "tagList", "tag", "website","userInfo"]),
    ...mapState({
      showTag: state => state.common.showTag,
    }),
    tagLen() {
      return this.tagList.length || 0;
    },
  },
  methods: {
    //offer选择的回调
    offerCallback(val) {
      this.$store.commit('SET_OFFER',val);
      getEventMgr('offerCenter').sendEvent({message: 'offerChanged', offerId: this.offerId});
      //this.$router.push({path: this.tagWel.value});
      //this.closeOthersTags()
    },

    //获取offer的字典
    getOfferDic() {
      getOfferList(this.userInfo.user_id).then(res => {
        this.offerList = res.data.data
        this.offerId = this.offer
        this.oc = store.state.user.oc
        this.offerId = store.state.user.offer
      })
    },

    getLastSameNameTag(item,fromIdx) {
      if(fromIdx >= this.tagList.length) {
        return item;
      }
      let lastItem = item;
      let name = this.generateTitle(item);
      for(let i=fromIdx;i<this.tagList.length;i++) {
        if(name == this.generateTitle(this.tagList[i])) {
          lastItem = this.tagList[i];
        }
      }
      return lastItem;
    },
    hasSameName(item,currIdx) {
      let name = this.generateTitle(item);
      for(let i=0;i<currIdx;i++) {
        if(name == this.generateTitle(this.tagList[i])) {
          return true;
        }
      }
      return false;
    },
    generateTitle(item) {
      return this.$router.$avueRouter.generateTitle(
        item.label,
        (item.meta || {}).i18n
      );
    },
    watchContextmenu(event) {
      if (!this.$el.contains(event.target) || event.button !== 0) {
        this.contextmenuFlag = false;
      }
      window.removeEventListener("mousedown", this.watchContextmenu);
    },
    handleContextmenu(event) {
      let target = event.target;
      // 解决 https://github.com/d2-projects/d2-admin/issues/54
      let flag = false;
      if (target.className.indexOf("el-tabs__item") > -1) flag = true;
      else if (target.parentNode.className.indexOf("el-tabs__item") > -1) {
        target = target.parentNode;
        flag = true;
      }
      if (flag) {
        event.preventDefault();
        event.stopPropagation();
        this.contentmenuX = event.clientX;
        this.contentmenuY = event.clientY;
        this.tagName = target.getAttribute("aria-controls").slice(5);
        this.contextmenuFlag = true;
      }
    },
    //激活当前选项
    setActive() {
      this.active = this.tag.value;
    },
    menuTag(value, action) {
      if (action === "remove") {
        let {tag, key} = this.findTag(value);
        this.$store.commit("DEL_TAG", tag);
        if (tag.value === this.tag.value) {
          tag = this.tagList[key === 0 ? key : key - 1]; //如果关闭本标签让前推一个
          this.openTag(tag);
        }
      }
    },
    openTag(item) {
      let tag;
      if (item.name) {
        tag = this.findTag(item.name).tag;
      } else {
        tag = item;
      }
      this.$router.push({
        path: this.$router.$avueRouter.getPath({
          name: tag.label,
          src: tag.value
        }, tag.meta),
        query: tag.query
      });
    },
    closeOthersTags() {
      this.contextmenuFlag = false;
      this.$store.commit("DEL_TAG_OTHER");
    },
    findTag(value) {
      let tag, key;
      this.tagList.map((item, index) => {
        if (item.value === value) {
          tag = item;
          key = index;
        }
      });
      return {tag: tag, key: key};
    },
    closeAllTags() {
      this.contextmenuFlag = false;
      this.$store.commit("DEL_ALL_TAG");
      this.$router.push({
        path: this.$router.$avueRouter.getPath({
          src: this.tagWel.value
        }),
        query: this.tagWel.query
      });
    },
    clearCacheTags() {
      this.$confirm("是否需要清除缓存?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        clearCache().then(() => {
          this.contextmenuFlag = false;
          this.$message.success('清除完毕');
        })
      });
    },
    viewOfferInfo() {
      let self = this;
      if(this.offerId != null && this.offerId != '') {
        self.offerInfo.title = 'check';
        self.offerInfo.open = true;
        self.offerInfo.visible = true;
        self.offerInfo.confirmToShare = 1;
        getDetail(this.offerId).then(res => {
          self.offerInfo.data = res.data.data;
        });
      }
    },
    closeOfferDialog() {
      this.offerInfo.visible = false;
    },
  }
};
</script>


